<template>
    <div class="timesite-container">
      <!-- 头部选择区域 -->
      <div class="header-section">
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="6">
            <el-select v-model="selectedType" placeholder="选择房型" style="width: 100%;" @change="handleRoomTypeChange">
              <el-option label="全部房型" value=""></el-option>
              <el-option
                v-for="type in roomTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleDateChange">
            </el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="refreshData">刷新</el-button>
          </el-col>
        </el-row>
      </div>
  
      <!-- 表格区域 -->
      <div class="table-section">
        <el-table 
          :data="roomData" 
          border 
          style="width: 100%"
          :height="tableHeight"
          v-loading="loading"
          element-loading-text="加载中..."
          element-loading-spinner="el-icon-loading">
          
  
          <el-table-column fixed="left" prop="roomInfo" label="房型" width="200">
            <template slot-scope="scope">
              <div>
                <div style="font-weight: bold; color: #303133;">{{ scope.row.roomName }}</div>
                <div style="font-size: 12px; color: #909399;">房号: {{ scope.row.roomNumber }}</div>
                <div style="font-size: 12px; color: #909399;">
                  条件: {{ scope.row.conditions }}
                </div>
                <div style="font-size: 12px; color: #909399;">
                  售价: ￥{{ scope.row.price }}
                </div>
                <div style="font-size: 12px; color: #909399;">
                  最低价: ￥{{ scope.row.minPrice }}
                </div>
                <div style="font-size: 12px; color: #909399; line-height: 1.6;">
                  房客: <span style="color: #C0C4CC;">👤</span>{{ scope.row.capacity }}
                </div>
              </div>
            </template>
          </el-table-column>
  
          <!-- 动态日期列 -->
          <el-table-column
            v-for="date in dateColumns"
            :key="date.date"
            :label="formatDateHeader(date)"
            :width="120"
            align="center">
            <template slot="header" slot-scope="scope">
              <div style="text-align: center;">
                <div style="font-weight: bold;">{{ date.weekDay }}</div>
                <div style="font-size: 12px;">{{ date.monthDay }}</div>
              </div>
            </template>
            <template slot-scope="scope">
              <div class="time-slot-cell">
                <div 
                  v-if="getRoomStatus(scope.row, date.date) === 'available'"
                  class="status-available">
                  已开房
                </div>
                <div 
                  v-else-if="getRoomStatus(scope.row, date.date) === 'booked'"
                  class="status-booked">
                  已关房
                </div>
                <div 
                  v-else
                  class="status-closed">
                  已关房
                </div>
                <div class="time-slot-info">
                  <div class="room-type">{{ scope.row.roomType }}</div>
                  <div class="price-info">
                    售价: ￥{{ getTimeslotInfo(scope.row, date.date).price }}
                  </div>
                  <div class="price-info">
                    最低价: ￥{{ getTimeslotInfo(scope.row, date.date).min_price }}
                  </div>
                  <div class="capacity-info">
                    <span class="user-icon">👤</span>{{ getTimeslotInfo(scope.row, date.date).capacity }}
                  </div>
                </div>
                <div class="edit-btn-container">
                  <el-button 
                    type="text" 
                    size="mini" 
                    class="edit-btn"
                    icon="el-icon-edit"
                    @click="editTimeSlot(scope.row, date.date)">
                    编辑
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
  
      <!-- 编辑时间段对话框 -->
      <el-dialog
        title="编辑时间段"
        :visible.sync="editDialogVisible"
        width="500px">
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="房间状态">
            <el-radio-group v-model="editForm.status">
              <el-radio label="available">已开房</el-radio>
              <el-radio label="closed">已关房</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="售价">
            <el-input-number 
              v-model="editForm.price" 
              :min="0" 
              :precision="2"
              controls-position="right">
            </el-input-number>
          </el-form-item>
          <el-form-item label="最低价">
            <el-input-number 
              v-model="editForm.minPrice" 
              :min="0" 
              :precision="2"
              controls-position="right">
            </el-input-number>
          </el-form-item>
          <el-form-item label="房客数">
            <el-input-number 
              v-model="editForm.capacity" 
              :min="1" 
              :max="10"
              controls-position="right">
            </el-input-number>
          </el-form-item>
          <el-form-item label="已预约房客数">
            <el-input-number 
              v-model="editForm.booked_count" 
              :min="0" 
              :max="10"
              controls-position="right">
            </el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTimeSlot">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { roomList, getTimeslotsByDateRange, updateTimeslot } from '@/api/mings'
  
  export default {
    name: 'TimeSite',
    data() {
      return {
        selectedType: '',
        dateRange: [],
        tableHeight: 600,
        editDialogVisible: false,
        editForm: {
          status: 'available',
          price: 0,
          minPrice: 0,
          capacity: 2,
          booked_count: 0
        },
        currentEditRoom: null,
        currentEditDate: null,
        currentTimeslotId: null,
        loading: false,
        
        // 房型选项
        roomTypes: [],
        
        // 房间数据
        roomData: [],
        
        // 时间段数据
        timeslotData: {},
        
        // 日期列
        dateColumns: [],
        
        // 商户ID（从store或route获取）
        merId: this.$store.getters.merId || 1
      }
    },
    
    mounted() {
      this.initializeDate()
      this.calculateTableHeight()
      this.loadRoomData()
      window.addEventListener('resize', this.calculateTableHeight)
    },
    
    beforeDestroy() {
      window.removeEventListener('resize', this.calculateTableHeight)
    },
    
    methods: {
      // 加载房间数据（直接从时间段接口获取）
      async loadRoomData() {
        try {
          this.loading = true
          await this.loadTimeslotData()
        } catch (error) {
          console.error('加载房间数据失败:', error)
          this.$message.error('加载数据失败')
        } finally {
          this.loading = false
        }
      },
      
      // 生成房型选项
      generateRoomTypes() {
        const types = [...new Set(this.roomData.map(room => room.roomType))]
        this.roomTypes = types.map(type => ({
          label: type,
          value: type
        }))
      },
      
      // 加载时间段数据
      async loadTimeslotData() {
        if (!this.dateRange || this.dateRange.length !== 2) return
        
        try {
          const res = await getTimeslotsByDateRange({
            mer_id: this.merId,
            start_date: this.dateRange[0],
            end_date: this.dateRange[1],
            room_type: this.selectedType
          })
          
          if (res.data) {
            // 适配您的接口数据结构
            this.roomData = []
            this.timeslotData = {}
            
            res.data.forEach(item => {
              // 简化房间数据转换
              const room = {
                id: item.room.id,
                roomName: item.room.title,
                roomNumber: item.room.id,
                roomType: '标准房',
                conditions: '可预约',
                price: parseFloat(item.room.price),
                minPrice: parseFloat(item.room.original_price) || parseFloat(item.room.price),
                capacity: 2,
                booked_count: 0
              }
              
              this.roomData.push(room)
              this.timeslotData[item.room.id] = item.timeslots
            })
            
            // 生成房型选项
            this.generateRoomTypes()
          }
          
        } catch (error) {
          console.error('加载时间段数据失败:', error)
        }
      },
      
      // 初始化日期
      initializeDate() {
        const today = new Date()
        const startDate = new Date(today)
        startDate.setDate(today.getDate() - 1) // 从昨天开始
        
        const endDate = new Date(today)
        endDate.setDate(today.getDate() + 13) // 到未来14天
        
        this.dateRange = [
          this.formatDate(startDate),
          this.formatDate(endDate)
        ]
        
        this.generateDateColumns()
      },
      
      // 生成日期列
      generateDateColumns() {
        this.dateColumns = []
        if (!this.dateRange || this.dateRange.length !== 2) return
        
        const startDate = new Date(this.dateRange[0])
        const endDate = new Date(this.dateRange[1])
        
        const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        
        for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
          const dateStr = this.formatDate(new Date(d))
          const weekDay = weekDays[d.getDay()]
          const monthDay = `${d.getMonth() + 1}-${d.getDate()}`
          
          this.dateColumns.push({
            date: dateStr,
            weekDay: weekDay,
            monthDay: monthDay
          })
        }
      },
      
      // 处理日期变化
      handleDateChange() {
        this.generateDateColumns()
        this.loadTimeslotData()
      },
      
      // 处理房型变化
      handleRoomTypeChange() {
        this.loadTimeslotData()
      },
      
      // 格式化日期
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },
      
      // 格式化日期头部
      formatDateHeader(date) {
        return `${date.weekDay} ${date.monthDay}`
      },
      
      // 获取房间状态
      getRoomStatus(room, date) {
        const timeslots = this.timeslotData[room.id]
        if (timeslots && timeslots[date]) {
          return timeslots[date].status
        }
        return 'closed' // 默认关房状态
      },
      
      // 获取时间段信息
      getTimeslotInfo(room, date) {
        const timeslots = this.timeslotData[room.id]
        if (timeslots && timeslots[date]) {
          return timeslots[date]
        }
        return {
          price: room.price,
          min_price: room.minPrice,
          capacity: room.capacity,
          booked_count: room.booked_count
        }
      },
      
      
      // 编辑时间段
      editTimeSlot(room, date) {
        this.currentEditRoom = room
        this.currentEditDate = date
        
        const timeslotInfo = this.getTimeslotInfo(room, date)
        const timeslots = this.timeslotData[room.id]
        this.currentTimeslotId = (timeslots && timeslots[date]) ? timeslots[date].id : null
        
        this.editForm = {
          status: this.getRoomStatus(room, date),
          price: timeslotInfo.price,
          minPrice: timeslotInfo.min_price,
          capacity: timeslotInfo.capacity,
          booked_count: timeslotInfo.booked_count
        }
        
        this.editDialogVisible = true
      },
      
      // 保存时间段
      async saveTimeSlot() {
        if (!this.currentEditRoom || !this.currentEditDate) return
        
        try {
          const data = {
            room_id: this.currentEditRoom.id,
            date: this.currentEditDate,
            status: this.editForm.status,
            price: this.editForm.price,
            min_price: this.editForm.minPrice,
            capacity: this.editForm.capacity,
            booked_count: this.editForm.booked_count
          }
          
          if (this.currentTimeslotId) {
            data.id = this.currentTimeslotId
          }
          
          await updateTimeslot(data)
          
          // 重新加载时间段数据
          await this.loadTimeslotData()
          
          this.$message.success('保存成功')
          this.editDialogVisible = false
          
        } catch (error) {
          console.error('保存失败:', error)
          this.$message.error('保存失败')
        }
      },
      
      // 刷新数据
      async refreshData() {
        await this.loadRoomData()
        this.$message.success('数据已刷新')
      },
      
      // 计算表格高度
      calculateTableHeight() {
        const windowHeight = window.innerHeight
        this.tableHeight = windowHeight - 200 // 减去头部和其他元素的高度
      }
    }
  }
  </script>
  
  <style scoped>
  .timesite-container {
    padding: 20px;
    background: #fff;
  }
  
  .header-section {
    margin-bottom: 20px;
  }
  
  .table-section {
    border: 1px solid #EBEEF5;
    border-radius: 4px;
  }
  
  .time-slot-cell {
    padding: 8px;
    min-height: 120px;
    position: relative;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .status-available {
    background-color: #E7F4FF;
    color: #409EFF;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 12px;
    text-align: center;
    margin-bottom: 5px;
  }
  
  .status-booked {
    background-color: #FEF0F0;
    color: #F56C6C;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 12px;
    text-align: center;
    margin-bottom: 5px;
  }
  
  .status-closed {
    background-color: #F5F7FA;
    color: #909399;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 12px;
    text-align: center;
    margin-bottom: 5px;
  }
  
  .time-slot-info {
    font-size: 12px;
    line-height: 1.5;
    margin-bottom: 8px;
    flex: 1;
  }
  
  .room-type {
    font-weight: bold;
    color: #303133;
    margin-bottom: 2px;
  }
  
  .price-info, .capacity-info {
    color: #606266;
    margin-bottom: 3px;
  }
  
  .user-icon {
    color: #C0C4CC !important;
    margin-right: 2px;
  }
  
  .edit-btn-container {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: auto;
    padding-top: 5px;
  }
  
  .edit-btn {
    font-size: 11px;
    padding: 4px 8px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 3px;
    color: #606266;
    display: flex;
    align-items: center;
    gap: 3px;
  }
  
  .edit-btn:hover {
    background-color: #ecf5ff;
    border-color: #b3d8ff;
    color: #409eff;
  }
  
  /* 表格样式调整 */
  ::v-deep .el-table {
    font-size: 12px;
  }
  
  ::v-deep .el-table th {
    background-color: #F5F7FA;
  }
  
  ::v-deep .el-table td {
    padding: 8px 0;
    vertical-align: top;
  }
  
  ::v-deep .el-table .cell {
    padding: 5px 8px;
    word-break: break-word;
  }
  
  /* 对话框样式 */
  .dialog-footer {
    text-align: right;
  }
  </style>
  